﻿using System;
using Epm.AppLogic.Framework;
using msBsc.Xsd.DataTds;
using System.Data;

namespace msBsc.AppLogic.DataAlc
{
    public class CBizDJkOrdersDetail : CustBizObject
    {
        private CDmDjkOrdersDetail m_CDmDjkDJkOrdersDetail = new CDmDjkOrdersDetail();
        private CDmDjkOrdersDetail oDmDjkDJkOrdersDetail
        {
            get { return m_CDmDjkDJkOrdersDetail; }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public CBizDJkOrdersDetail()
            : base()
        {
            this.DataObj = new CDbAccess();
            this.DataObj.Init(this.m_CDmDjkDJkOrdersDetail.DJK_ORDERS_DETAIL);
            this.TableName = this.DataObj.TableName;
            this.DataObj.KeyField = this.DataObj.Fields["ORDERS_DETAIL_ID"];
        }

        /// <summary>
        /// 新增记录前的处理
        /// </summary>
        /// <param name="drw">新增数据行</param>
        /// <returns>true/false</returns>
        /// <remarks>
        /// 生成ID值
        /// </remarks>
        protected override bool BeforeRowAdded(DataRow drw)
        {
            if (drw[this.KeyFieldName].ToString().Length < 10)
            {
                drw[this.KeyFieldName] = this.DataObj.NewID();
            }
            return true;
        }

        /// <summary>
        /// 记录修改前检验
        /// </summary>
        /// <param name="drw">当前记录</param>
        /// <returns>>校验合法，返回值为true,否则返回false</returns>
        /// <remarks>
        /// ID不允许修改,并把此修改操作记录到BSE_MODIFY_HISTORY表中
        /// </remarks>
        protected override bool BeforeRowModified(DataRow drw)
        {
            //ID不容许修改
            if (drw[this.KeyFieldName].ToString() != drw[this.KeyFieldName, DataRowVersion.Original].ToString())
            {
                Exception e = new Exception(this.TableName + "表的主键" + this.KeyFieldName + "字段不允许被修改");
                throw e;
            }
            return true;
        }
        protected override bool BeforeRowDeletedR(DataRow drw)
        {
            //using (msBsc.AppLogic.DataAlc.CBizShpPageColumn objtem = new CBizShpPageColumn())
            //{
            //    DataSet ds = objtem.SelectByPageNo(this.GetRowStr(drw, KeyFieldName));
            //    for (int i = ds.Tables[0].Rows.Count - 1; i >= 0; i--)
            //    {
            //        ds.Tables[0].Rows[i].Delete();
            //    }
            //    objtem.Update(ds);
            //} 
            return true;
        }

        protected override bool AfterRowAdded(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowModified(DataRow drw)
        {
            return true;
        }

        protected override bool AfterRowDeletedR(DataRow drw)
        {
            return true;
        }

        /// <summary>
        /// 添加订单明细
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="productIds">产品编号</param>
        /// <param name="days">服务天数</param>
        /// <param name="addType">添加类型(1、包车，2、服务)</param>
        /// <returns></returns>
        public DataSet AddOrderDetail(string orderId, string productIds, int days, int addType, out string solderid)
        {
            solderid = string.Empty;
            DataSet ds = new CDmDjkOrdersDetail();
            if (string.IsNullOrEmpty(orderId)
                || string.IsNullOrEmpty(productIds))
            {
                return ds;
            }

            switch (addType)
            {
                case 1:
                    DataSet dsVehicleInfo = GetVehicleInfo(productIds);
                    if (dsVehicleInfo == null || dsVehicleInfo.Tables[0].Rows.Count <= 0)
                    {
                        return ds;
                    }
                    ds = AddVehicleToOrder(orderId, days, addType, dsVehicleInfo, ds);
                    break;
                case 2:
                    break;
            }

            ds.Tables[0].TableName = this.TableName;
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                this.Update(ds);
            }
            return ds;
        }

        /// <summary>
        /// 添加车辆信息到订单详情
        /// </summary>
        /// <param name="vehicleDs">车辆信息数据集</param>
        /// <returns></returns>
        private DataSet AddVehicleToOrder(string orderId, int days, int productType, DataSet sourceDs, DataSet resultDs)
        {
            if (sourceDs == null
                || sourceDs.Tables[0].Rows.Count <= 0)
            {
                return resultDs;
            }

            foreach (DataRow item in sourceDs.Tables[0].Rows)
            {
                DataRow dr = resultDs.Tables[0].NewRow();
                dr["ORDERS_DETAIL_ID"] = this.DataObj.NewID();
                dr["ORDERS_INFO_ID"] = orderId;
                dr["PRODUCT_TYPE"] = productType;
                dr["PRODUCT_ID"] = item["PRODUCT_ID"];
                dr["PRODUCT_NME"] = item["PRODUCT_NAME"];
                dr["IMG_URL"] = item["PRODUCT_PIC"];
                dr["PRODUCT_QTY"] = days;
                dr["PRODUCT_STRIKE_PRICE"] = item["PRODUCT_PRICE"];
                dr["DISCOUNT_AMT"] = 0;
                dr["PRODUCT_SEATS"] = item["PRODUCT_SEATS"];
                dr["PRODUCT_SERVICE_TYPE"] = item["PRODUCT_SERVICE_TYPE"];

                resultDs.Tables[0].Rows.Add(dr);
            }
            return resultDs;
        }


        /// <summary>
        /// 获取车辆信息
        /// </summary>
        /// <param name="vehicleIds">车辆编号</param>
        /// <returns></returns>
        public DataSet GetVehicleInfo(string vehicleIds)
        {

            string[] productsId = vehicleIds.Split('|');
            if (productsId.Length < 1)
            {
                return null;
            }
            System.Text.StringBuilder sbSql = new System.Text.StringBuilder("SELECT VEHICLE_INFO_ID PRODUCT_ID,VEHICLE_NAME PRODUCT_NAME,VEHICLE_DEFAULT_PIC PRODUCT_PIC,VEHICLE_PRICE_DAY PRODUCT_PRICE,DJACK_ID PERSON_ID,VEHICLE_SEATS PRODUCT_SEATS,VEHICLE_SERVICE_TYPE PRODUCT_SERVICE_TYPE FROM DJK_VEHICLE_INFO ");

            sbSql.Append(" WHERE VEHICLE_INFO_ID= '" + productsId[0] + "' ");
            for (int i = productsId.Length - 1; i > 0; i--)
            {
                sbSql.Append(" OR VEHICLE_INFO_ID= '" + productsId[i] + "' ");
            }

            return this.DataObj.QueryBySQL(sbSql.ToString());
        }

        /// <summary>
        /// 获取服务信息
        /// </summary>
        /// <param name="serviceIds">服务编号</param>
        /// <returns></returns>
        private DataSet GetServiceInfo(string serviceIds)
        {
            DataSet ds;
            string[] productsId = serviceIds.Split('|');
            System.Text.StringBuilder sbSql = new System.Text.StringBuilder("SELECT SERVICE_ID,SERVICE_NME,SERVICE_STRIKE_PRICE FROM DJK_SERVICE_INFO WHERE 1<>1");

            for (int i = productsId.Length - 1; i >= 0; i--)
            {
                sbSql.Append(" OR SERVICE_ID=" + productsId[i]);
            }
            ds = this.DataObj.QueryBySQL(sbSql.ToString());
            return ds;
        }

        /// <summary>
        /// 判断该车辆和订单是否 存在
        /// </summary>
        /// <param name="ordesInfoId">订单ID</param>
        /// <param name="productID">车辆、产品ID</param>
        /// <returns></returns>
        public bool OrdersWhetherThere(string ordesInfoId, string productID)
        {
            if (string.IsNullOrEmpty(ordesInfoId) || string.IsNullOrEmpty(productID)) { return false; }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("ordersid", ParameterDirection.Input, EDbType.String, 36, ordesInfoId));
            parmCollection.Add(new CDbParm("productid", ParameterDirection.Input, EDbType.String, 36, productID));

            DataSet ds = this.DataObj.QueryBySQL(@"SELECT COUNT(1) CT FROM DJK_ORDERS_DETAIL WHERE  ORDERS_INFO_ID=@ordersid AND PRODUCT_ID=@productid", parmCollection);

            return Convert.ToInt32(ds.Tables[0].Rows[0]["CT"]) > 0;

        }
        /// <summary>
        /// 修改订单明细信息
        /// </summary>
        /// <param name="detailId"></param>
        /// <param name="discountAMT"></param>
        /// <returns>总共优惠价格</returns>
        public decimal ModifyProduct(string detailId, decimal discountAMT)
        {
            DataSet ds = GetDetailById(detailId);
            if (ds == null
                || ds.Tables[0].Rows.Count != 1)
            {
                return 0;
            }
            decimal prevDis;
            decimal.TryParse(ds.Tables[0].Rows[0]["DISCOUNT_AMT"].ToString(), out prevDis);
            int productNum;
            int.TryParse(ds.Tables[0].Rows[0]["PRODUCT_QTY"].ToString(), out productNum);

            decimal totalDis = (discountAMT - prevDis) * productNum;

            ds.Tables[0].Rows[0]["DISCOUNT_AMT"] = discountAMT;
            this.Update(ds);
            return totalDis;
        }

        /// <summary>
        /// 根据编号获取订单明细信息
        /// </summary>
        /// <param name="detailId">明细编号</param>
        /// <returns></returns>
        public DataSet GetDetailById(string detailId)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_DETAIL WHERE ORDERS_DETAIL_ID='" + detailId + "'");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 根据订单编号获取订单完整信息(包含订单信息，订单明细， 用户信息)
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        public DataSet GetOrderDetailsById(string orderId, bool isDjack)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return null;
            }

            if (string.IsNullOrEmpty(msBsc.SvRef.UserInfo.Operator))
            {
                return null;
            }

            string currIsDajck = isDjack ? "Y" : "N";

            //if (msBsc.SvRef.UserInfo.OperType == "1")
            //{
            //    currIsDajck = "N";
            //}
            //else if (msBsc.SvRef.UserInfo.OperType == "2")
            //{
            //    currIsDajck = "Y";
            //}
            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("orderId", ParameterDirection.Input, EDbType.String, 36, orderId));
            parmCollection.Add(new CDbParm("isDjack", ParameterDirection.Input, EDbType.String, 36, currIsDajck));
            parmCollection.Add(new CDbParm("custId", ParameterDirection.Input, EDbType.String, 36, msBsc.SvRef.UserInfo.Operator));

            DataSet ds = this.DataObj.QueryBySP("DJK_SELECT_ORDERS_DETAIL_FOR_VIEW", parmCollection);
            return ds;
        }

        /// <summary>
        /// 根据订单ID 获取订单明细信息
        /// </summary>
        /// <param name="ORDERS_INFO_ID">订单ID</param>
        /// <returns></returns>
        public DataSet GetDetailByOrderInfoID(string ORDERS_INFO_ID)
        {
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_DETAIL WHERE ORDERS_INFO_ID='" + ORDERS_INFO_ID + "'");
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }

        /// <summary>
        /// 修改订单 减免价格
        /// </summary>
        /// <param name="orderid">订单id</param>
        /// <param name="userid">地接客 id</param>
        /// <param name="detailList">订单明细</param>
        /// <param name="bili">订单比例</param>
        /// <returns></returns>
        /// Author:蒲崇彬
        /// Creation date:2014-6-11 13:40
        public string[] UpdateDetailPrice(string orderid, string userid, string detailList, decimal bili)
        {
            if (string.IsNullOrEmpty(userid))
            {
                return new string[] { "false", "登录失效请重新登录" };
            }
            if (string.IsNullOrEmpty(orderid))
            {
                return new string[] { "false", "订单ID错误,请重新操作." };
            }
            if (string.IsNullOrEmpty(detailList))
            {
                return new string[] { "false", "你修改的订单详情不存在" };
            }
            string[] detailKeyVal = detailList.Split('|');

            //事物
            string retJson = string.Empty;
            decimal priceSum = 0, priceAmt = 0;

            System.Transactions.TransactionOptions transactionOption = new System.Transactions.TransactionOptions();
            transactionOption.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
            transactionOption.Timeout = new TimeSpan(0, 10, 0);
            using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, transactionOption))
            {
                using (msBsc.AppLogic.DataAlc.CBizOrdersInfo orderinfo = new AppLogic.DataAlc.CBizOrdersInfo())
                {
                    DataSet dsOrderInfo = orderinfo.GetOrderInfoByUserAndOrderId(orderid, userid);
                    if (dsOrderInfo == null || dsOrderInfo.Tables[0].Rows.Count < 1)
                    {
                        return new string[] { "false", "该订单号不存在,请重新操作." };
                    }
                    if (this.dtCurrDateTime >= Convert.ToDateTime(dsOrderInfo.Tables[0].Rows[0]["ORDER_START_TIME"].ToString()))
                    {
                        return new string[] { "false", "当前状态已过期，不能修改价格" };
                    }
                    //获取订单明细
                    DataSet dsDetail = GetDetailByOrderInfoID(orderid);
                    if (dsDetail == null || dsDetail.Tables[0].Rows.Count < 1)
                    {
                        return new string[] { "false", "订单ID错误,没有找到要修改的明显信息." };
                    }

                    bool isTrue = false;

                    //验证 服务器是否存在该订单详情  如果有就修改，没有就提示
                    foreach (DataRow item in dsDetail.Tables[0].Rows)
                    {
                        isTrue = false;

                        foreach (var detail in detailKeyVal)
                        {
                            if (!string.IsNullOrEmpty(detail))
                            {
                                string[] tempDetail = detail.Split(',');
                                if (item["ORDERS_DETAIL_ID"].ToString() == tempDetail[0].Trim())
                                {
                                    //优惠价格 必须小于 产品价格
                                    if (Convert.ToDecimal(item["PRODUCT_STRIKE_PRICE"].ToString()) < Convert.ToDecimal(tempDetail[1]))
                                    {
                                        return new string[] { "false", "优惠价格必须小于产品价格。" };
                                    }

                                    //修改
                                    item["DISCOUNT_AMT"] = tempDetail[1];
                                    priceAmt += Convert.ToDecimal(tempDetail[1]) * Convert.ToDecimal(item["PRODUCT_QTY"]);
                                    isTrue = true;
                                    break;
                                }
                            }
                        }
                        if (!isTrue)
                        {
                            return new string[] { "false", "订单明细不存在，请重新提交数据" };
                        }
                        //订单总价计算
                        priceSum += Convert.ToDecimal(item["PRODUCT_STRIKE_PRICE"]) * Convert.ToDecimal(item["PRODUCT_QTY"]);
                    }
                    //修改当价格
                    this.Update(dsDetail);
                    //修改主订单 总价格
                    dsOrderInfo.Tables[0].Rows[0]["ORDER_TOTAL_BALANCE"] = priceSum;
                    dsOrderInfo.Tables[0].Rows[0]["DISCOUNT_AMT"] = priceAmt;
                    dsOrderInfo.Tables[0].Rows[0]["PAYABLE_AMT"] = (priceSum - priceAmt) * bili;
                    dsOrderInfo.Tables[0].Rows[0]["DEPOSIT_RATIO"] = bili;
                    orderinfo.Update(dsOrderInfo);

                    retJson = msBsc.AppLogic.Cfg.HttpTools.GetJsonByTable(dsDetail.Tables[0], "", "", 1, 30, "");
                    ts.Complete();
                }

                //修改成功 刷新价格
                return new string[] { "true", priceSum.ToString(), priceAmt.ToString(), retJson };
            }
        }

        /// <summary>
        /// 添加订单明细
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <param name="productIds">产品编号</param>
        /// <param name="days">服务天数</param>
        /// <param name="addType">添加类型(1、包车，2、服务)</param>
        /// <returns></returns>
        /// Author:蒲崇彬
        /// Creation date:2014-6-11 13:20
        public DataSet AddOrderDetailN(string orderId, DataSet products, int days, int addType = 1)
        {
            if (string.IsNullOrEmpty(orderId))
            {
                return null;
            }
            DataSet ds = new CDmDjkOrdersDetail();
            switch (addType)
            {
                case 1:
                    ds = AddVehicleToOrder(orderId, days, addType, products, ds);
                    break;
                case 2:
                    break;
            }

            ds.Tables[0].TableName = this.TableName;
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                this.Update(ds);
            }
            return ds;
        }


        /// <summary>
        /// 根据订单ID 获取订单明细信息
        /// </summary>
        /// <param name="ORDERS_INFO_ID">订单ID  主键ID</param>
        /// <param name="productid">产品id</param>
        /// <returns></returns>
        public DataSet GetDetailInfo(string ORDERS_INFO_ID, string productid)
        {

            if (string.IsNullOrEmpty(ORDERS_INFO_ID) || string.IsNullOrEmpty(productid))
            {
                return null;
            }

            CDbParmCollection parmCollection = new CDbParmCollection();
            parmCollection.Add(new CDbParm("ORDERS_INFO_ID", ParameterDirection.Input, EDbType.String, 36, ORDERS_INFO_ID));
            parmCollection.Add(new CDbParm("PRODUCT_ID", ParameterDirection.Input, EDbType.String, 36, productid));
            DataSet ds = this.DataObj.QueryBySQL(@"SELECT * FROM DJK_ORDERS_DETAIL WHERE ORDERS_INFO_ID=@ORDERS_INFO_ID AND PRODUCT_ID=@PRODUCT_ID", parmCollection);
            ds.Tables[0].TableName = this.TableName;
            return ds;
        }
    }

}
